package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.jzo2o.common.utils.LambdaUtils;
import com.jzo2o.es.core.ElasticSearchTemplate;
import com.jzo2o.foundations.model.domain.ServeAggregation;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.IServeAggregationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ServeAggregationServiceImpl implements IServeAggregationService {

    @Resource
    private ElasticSearchTemplate elasticSearchTemplate;

    @Override
    public List<ServeSimpleResDTO> findServeList(String cityCode, String keyword, Long serveTypeId) {
        // 1、封装查询条件
        SearchRequest.Builder builder = new SearchRequest.Builder();
        builder.index("serve_aggregation");//指定搜索的索引库

        // 构造BoolQuery
        builder.query(boolQuery -> {
            // bool条件
            return boolQuery.bool(bool -> {
                // must条件
                if (ObjectUtil.isNotEmpty(keyword)) {
                    bool.must(mustQuery ->
                            // multiMatch模糊搜索
                            mustQuery.multiMatch(multiMatch ->
                                    multiMatch.fields("serve_item_name", "serve_type_name").query(keyword)));
                }

                //匹配服务类型
                if (ObjectUtil.isNotEmpty(serveTypeId)) {
                    bool.must(must->
                            must.term(term->
                                    term.field(LambdaUtils.getUnderLineFieldName(ServeAggregation::getServeTypeId)).value(serveTypeId)));
                };
                // 过滤条件
                bool.filter(filterQuery ->
                    // term城市过滤条件
                     filterQuery.term(term ->
                             term.field("city_code").value(cityCode)));
                return bool;
            });
        });
        // 2、排序
        builder.sort(SortOptions.of(sortQuery -> sortQuery.field(fieldQuery -> fieldQuery.field("serve_item_sort_num").order(SortOrder.Asc))));
        // 3、执行搜索
        SearchResponse<ServeAggregation> response = elasticSearchTemplate.opsForDoc().search(builder.build(), ServeAggregation.class);

        // 4、解析结果集
        List<ServeAggregation> list = response.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
        List<ServeSimpleResDTO> serveSimpleResDTOS = BeanUtil.copyToList(list, ServeSimpleResDTO.class);
        return serveSimpleResDTOS;
    }
}
